package com.xuelang.pipeline.worker.app.common.util;

import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;

import java.io.IOException;
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @author liuyuan.ly
 * @since 2024/6/13 15:11
 */
public class OffsetDateTimeAdapter extends TypeAdapter<OffsetDateTime> {

    private static final DateTimeFormatter formatter = DateTimeFormatter.ISO_OFFSET_DATE_TIME;

    @Override
    public void write(JsonWriter jsonWriter, OffsetDateTime value) throws IOException {
        if (value != null) {
            jsonWriter.value(value.format(formatter));
        } else {
            jsonWriter.nullValue();
        }
    }

    @Override
    public OffsetDateTime read(JsonReader jsonReader) throws IOException {
        if (jsonReader != null) {
            return OffsetDateTime.parse(jsonReader.nextString(), formatter);
        } else {
            return null;
        }
    }
}
